home *** CD-ROM | disk | FTP | other *** search
- Path: prairienet.org!wemccaug
- From: wemccaug@prairienet.org (Wendy E. McCaughrin)
- Newsgroups: comp.lang.c++
- Subject: RE: Proper use of friend keyword
- Date: 13 Apr 1996 22:55:33 GMT
- Organization: University of Illinois at Urbana
- Message-ID: <4kpbd5$spq@vixen.cso.uiuc.edu>
- References: <00001a81+0000b164@msn.com> <4jn38u$j9c@holly.ACNS.ColoState.EDU>
- Reply-To: wemccaug@prairienet.org (Wendy E. McCaughrin)
- NNTP-Posting-Host: firefly.prairienet.org
-
-
- Reply-To: wemccaug@prairienet.org
-
- In a previous article, Steve_Quist@msn.com (Stephen Quist) says:
-
- >Corby Hudnall wrote:
- >
- >Hey all, I have a question about how to use the friend keyword. Consider
- >the following example:
- >
- >class.h---------
- >class ABC
- >{
- > int AValue;
- > int GetAValue() { return (AValue); }
- >public:
- > ABC() { AValue=5; }
- > ~ABC(){ }
- >};
- >
- >class XYZ
- >{
- >public:
- > XYZ() { }
- > ~XYZ() { }
- > friend int ABC::GetAValue();
- >};
- >
- >prog.C--------------------
- >#include <iostream.h>
- >#include "class.h"
- >
- >void main()
- >{
- > ABC abc;
- > XYZ xyz;
- >
- > cout << xyz.GetAValue() << endl
- >}
- >
- >
- >when I try to compile this, I get the message "no member funciton
- >'XYZ::GetAValue()' defined." What do I need to do in order to
- >make this work. Thanks for any and all suggestions.
- >-----------------
- >Well, the compiler is of course right. I am not sure what you are
- >trying to do. If you are trying to make GetAValue() a mf of XYZ
- >then ABC and XYZ should have an inheritance relationship.
-
- What??? This has nothing to do with inheritance whatsoever. The
- compiler only rejected the statement because the XYZ object xyz
- contains no member function named GetAValue(). Furthermore, this
- is not responsive to the author's question, which is about how
- to use the 'friend' keyword. Its use was legal but inappropriate
- since GetAValue() never accesses XYZ's data members (in fact, there
- are none to access). The right answer to that question is:
-
- 1. Give XYZ some data members to access and then redo
- GetAValue() to access them in its code body;
-
- 2. Since GetAValue() _is_ a member of the ABC object abc,
- redo the cout to contain a call to abc.GetAValue().
-
- Finally, some sort of forward declaration is needed for GetAValue()
- to access the as-yet-undelcared class XYZ's data member(s). Best
- way is to reverse the order of delcarations, using the 'friend'
- declaration as the forward reference to class ABC.
-